package com.jhd.fuzhou.view.receipt;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.downloadmanager.manager.fileload.FileLoadingBean;
import com.jhd.fuzhou.service.ArchiveService;
import com.jhd.fuzhou.service.LoginService;
import com.jhd.fuzhou.service.ProcessService;
import com.jhd.fuzhou.service.ReceiveService;
import com.jhd.fuzhou.service.SupervisionService;
import com.jhd.fuzhou.util.CustomToast;
import com.jhd.fuzhou.util.ReceiptProcess;
import com.jhd.fuzhou.util.UtilHelper;
import com.jhd.fuzhou.view.login.BaseActivity;
import com.jhd.fuzhou.view.login.FuzhouApplication;
import com.jhd.fuzhou.view.task.AuditTaskActivity;
import com.jhd.fuzhou.vo.ArchivesFileVo;
import com.jhd.fuzhou.vo.GlobalDictionaryVo;
import com.jhd.fuzhou.vo.JsonForResult;
import com.jhd.fuzhou.vo.ProInstance;
import com.jhd.fuzhou.vo.Process;
import com.jhd.fuzhou.vo.ReceiveReportReadPersonVo;
import com.jhd.fuzhou.vo.ReceiveReportVo;

import net.zigin.commons.util.ParamsMapUtil;
import net.zigin.commons.util.StringUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class ReceiptDetailActivity extends BaseActivity {

    @BindView(R.id.tv_DocName)TextView tv_DocName;//文件名称
    @BindView(R.id.tv_communication_authority)TextView tv_communication_authority;//来文机关
    @BindView(R.id.tv_letter_number)TextView tv_letter_number;//来文字号
    @BindView(R.id.tv_create_date)TextView tv_create_date;//来文日期
    @BindView(R.id.tv_punish_date)TextView tv_punish_date;//分发日期
    @BindView(R.id.tv_accept_unit)TextView tv_accept_unit;//接受单位
    @BindView(R.id.tv_instruction_sheet)TextView tv_instruction_sheet;//批示单名称
    @BindView(R.id.tv_accept_order)TextView tv_accept_order;//收文顺序
    @BindView(R.id.tv_accept_type)TextView tv_accept_type;//文件类型
    @BindView(R.id.tv_secrecy_level)TextView tv_secrecy_level;//保密级别
    @BindView(R.id.tv_post_person)TextView tv_post_person;//发文人
    @BindView(R.id.tv_status)TextView tv_status;//状态
    @BindView(R.id.rel_document)RelativeLayout rel_document;//文书附件
    @BindView(R.id.rv_step)RecyclerView rv_step;//流程
    @BindView(R.id.btn_post)Button btn_post;//流程
    private Context context=this;
    private List<ArchivesFileVo> archivesFileVos;
    private List<Process> processList=new ArrayList<>();
    private ProInstance proInstance;
    private String id,data;
    private ReceiveReportVo receiveReportVo;
    private List<ReceiveReportReadPersonVo> receiveReportReadPersonVoList=new ArrayList<>();

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_receipt_detail);
    }

    @Override
    protected void processLogic() {
        application.addTaskActivity(this);
        onBack();
        data = getIntent().getStringExtra("data");
        receiveReportVo= JSON.parseObject(data, ReceiveReportVo.class);
        setData(receiveReportVo);
    }
    private void setData(ReceiveReportVo receiveReportVo){
        getArchivesFilesById(receiveReportVo.getId());
        getReceiveReportInfoById(receiveReportVo.getId());
        tv_DocName.setText(StringUtil.isNullOrEmpty(receiveReportVo.getReportTitle())?"":receiveReportVo.getReportTitle());
        tv_communication_authority.setText(StringUtil.isNullOrEmpty(receiveReportVo.getDistributeUnitName())?"":receiveReportVo.getDistributeUnitName());
        tv_letter_number.setText(StringUtil.isNullOrEmpty(receiveReportVo.getReachReportNum())?"":receiveReportVo.getReachReportNum());
        if(!StringUtil.isNullOrEmpty(receiveReportVo.getReachReportDate()))tv_create_date.setText(receiveReportVo.getReachReportDate().substring(0,11));
        if(!StringUtil.isNullOrEmpty(receiveReportVo.getDistributeDate()))tv_punish_date.setText(receiveReportVo.getDistributeDate().substring(0,11));
        setUnit();
        tv_instruction_sheet.setText(StringUtil.isNullOrEmpty(receiveReportVo.getInstructionBillName())?"":receiveReportVo.getInstructionBillName());
        tv_accept_order.setText(StringUtil.isNullOrEmpty(receiveReportVo.getReceiveReportNum())?"":receiveReportVo.getReceiveReportNum());
        tv_accept_type.setText(StringUtil.isNullOrEmpty(receiveReportVo.getFileType())?"":receiveReportVo.getFileType());
        tv_secrecy_level.setText(StringUtil.isNullOrEmpty(receiveReportVo.getReportTitle())?"":receiveReportVo.getSecurityLevel());
        tv_post_person.setText(StringUtil.isNullOrEmpty(receiveReportVo.getDistributePersonName())?"":receiveReportVo.getDistributePersonName());
        if(!StringUtil.isNullOrEmpty(receiveReportVo.getReportStatus()))tv_status.setText(receiveReportVo.getReportStatus());
        btn_post.setText(receiveReportVo.getLookUpAndComment()?"阅文意见":"审核");
    }

    private void setUnit(){
        if(receiveReportVo.getReceiveOffices()!=null){
            String ss="";
            for (String receiveOffice : receiveReportVo.getReceiveOffices()) {
                if(ss.equals("")){
                    ss=receiveOffice;
                }else{
                    ss=ss+","+receiveOffice;
                }
            }
            tv_accept_unit.setText(ss);
        }
    }

    public void addReadAdvise(String id,String advise){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        ReceiveService vs = retrofit.create(ReceiveService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("id",id).addParam("hasRead","1").addParam("userName",application.getUserName()).addParam("advise",advise);
        Call<JsonForResult> jsonForResultCall = vs.addReadAdvise(application.getAccessToken(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        getReadPersonRecord(receiveReportVo.getId());
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    @OnClick({R.id.rel_document,R.id.btn_post})
    public void onClick(View v){
        Gson gson=new Gson();
        switch (v.getId()){
            case R.id.rel_document:
                Intent intent=new Intent(context,ReceiptDocumentActivity.class);
                intent.putExtra("data", gson.toJson(archivesFileVos));
                startActivity(intent);
                break;
            case R.id.btn_post:
                if("审核".equals(btn_post.getText().toString())){
                    Intent intent2=new Intent(context, AuditReceiptActivity.class);
                    intent2.putExtra("data", new Gson().toJson(receiveReportVo));
                    if(receiveReportVo.getMyTask()&&("主管领导审核".equals(receiveReportVo.getProgress()))){
                        intent2.putExtra("status","撤销审核");
                    }else{
                        intent2.putExtra("status","审核");
                    }
                    intent2.putExtra("proInstance",proInstance.getProcessInstanceId());
                    startActivityForResult(intent2,1);
                }else{
                    Intent intent2=new Intent(context, ReadingCommentActivity.class);
                    intent2.putExtra("advise", receiveReportVo.getAdvise());
                    intent2.putExtra("id", receiveReportVo.getId());
                    startActivityForResult(intent2,1);
                }
                break;
        }
    }

    private void getReadPersonRecord(String id){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        ReceiveService vs = retrofit.create(ReceiveService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("id",id);
        Call<JsonForResult> jsonForResultCall = vs.getReadPersonRecord(application.getAccessToken(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if (jsonForResult.getData() != null) {
                            receiveReportReadPersonVoList = JSON.parseArray(jsonForResult.getData().toString(), ReceiveReportReadPersonVo.class);
                            if(processList!=null||receiveReportReadPersonVoList!=null){
                                LinearLayoutManager manager=new LinearLayoutManager(context);
                                rv_step.setLayoutManager(manager);
                                StepAdapter adapter=new StepAdapter(processList,receiveReportReadPersonVoList);
                                rv_step.setAdapter(adapter);
                            }
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg;
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }

    private void getArchivesFilesById(String id){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        ArchiveService vs = retrofit.create(ArchiveService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("archivesId",id);
        Call<JsonForResult> jsonForResultCall = vs.getArchivesFilesById(application.getAccessToken(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if (jsonForResult.getData() != null) {
                            archivesFileVos = JSON.parseArray(jsonForResult.getData().toString(), ArchivesFileVo.class);
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg;
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    private void getReceiveReportInfoById(String id){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        ReceiveService vs = retrofit.create(ReceiveService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("id",id);
        Call<JsonForResult> jsonForResultCall = vs.getReceiveReportInfoById(application.getAccessToken(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        String process=receiveReportVo.getProgress();
                        boolean myTask=receiveReportVo.getMyTask();String taskId=receiveReportVo.getTaskId();
                        receiveReportVo=JSON.parseObject(jsonForResult.getData().toString(), ReceiveReportVo.class);
                        receiveReportVo.setProgress(process);
                        receiveReportVo.setMyTask(myTask);receiveReportVo.setTaskId(taskId);
                        setUnit();
                        getProInstanceId(receiveReportVo.getId());
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg;
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }

    public void getProInstanceId(String id){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        ProcessService vs = retrofit.create(ProcessService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("businessKey",id);
        Call<JsonForResult> jsonForResultCall = vs.getProInstanceId(application.getAccessToken(),application.getUserName(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if(jsonForResult.getData()!=null){
                            proInstance= JSON.parseObject(jsonForResult.getData().toString(), ProInstance.class);
                            list(proInstance.getProcessInstanceId());
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    private void list(String id){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        ProcessService vs = retrofit.create(ProcessService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("procInstId",id);
        Call<JsonForResult> jsonForResultCall = vs.list(application.getAccessToken(),application.getUserName(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if (jsonForResult.getData() != null) {
                            processList = JSON.parseArray(jsonForResult.getData().toString(), Process.class);
                            getReadPersonRecord(receiveReportVo.getId());
                            //已阅操作在填写意见后再执行
                            /*if(btn_post.getText().toString().equals("阅文意见")&&receiveReportVo.getAdvise()==null){
                                addReadAdvise(receiveReportVo.getId(),"已阅");
                            }else{
                                getReadPersonRecord(receiveReportVo.getId());
                            }*/
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg;
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
    public class StepAdapter extends RecyclerView.Adapter<StepAdapter.ViewHolder> {
        private List<Process> processList;private List<ReceiveReportReadPersonVo> receiveReportReadPersonVoList;

        public StepAdapter(List<Process> processList,List<ReceiveReportReadPersonVo> receiveReportReadPersonVoList) {
            this.processList = processList;
            this.receiveReportReadPersonVoList = receiveReportReadPersonVoList;
        }

        @NonNull
        @Override
        public StepAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_process_step, parent, false);
            StepAdapter.ViewHolder viewHolder = new StepAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull StepAdapter.ViewHolder holder, int position) {
            if(processList!=null&&position<processList.size()){
                if("审核未通过".equals(processList.get(position).getStatus())){
                    holder.image.setBackgroundResource(R.drawable.red_round_background);
                    holder.tv_status.setBackgroundResource(R.drawable.text_orange_background);
                    holder.tv_status.setTextColor(getResources().getColor(R.color.red));
                }
                if(StringUtil.isNullOrEmpty(processList.get(position).getMessage()))holder.tv_suggest.setVisibility(View.GONE);
                holder.tv_status.setText(StringUtil.isNullOrEmpty(processList.get(position).getStatus())?"":processList.get(position).getStatus());
                holder.tv_suggest.setText(StringUtil.isNullOrEmpty(processList.get(position).getMessage())?"":processList.get(position).getMessage());
                holder.tv_date.setText(StringUtil.isNullOrEmpty(processList.get(position).getStartTime())?"":processList.get(position).getStartTime());
                if(position==0){
                    holder.tv_person.setText("拟稿人:"+(StringUtil.isNullOrEmpty(processList.get(position).getName())?"":processList.get(position).getName()));
                }else{
                    holder.tv_person.setText("审核人:"+(StringUtil.isNullOrEmpty(processList.get(position).getName())?"":processList.get(position).getName()));
                }
            }
            if(receiveReportReadPersonVoList!=null){
                if(processList!=null&&position<processList.size()+receiveReportReadPersonVoList.size()&&position>=processList.size()){
                    holder.tv_status.setText("已阅");
                    holder.tv_suggest.setText(StringUtil.isNullOrEmpty(receiveReportReadPersonVoList.get(position-processList.size()).getAdvise())?"":receiveReportReadPersonVoList.get(position-processList.size()).getAdvise());
                    holder.tv_date.setText(StringUtil.isNullOrEmpty(receiveReportReadPersonVoList.get(position-processList.size()).getReadTime())?"":receiveReportReadPersonVoList.get(position-processList.size()).getReadTime());
                    holder.tv_person.setText("阅文人:"+(StringUtil.isNullOrEmpty(receiveReportReadPersonVoList.get(position-processList.size()).getUserName())?"":receiveReportReadPersonVoList.get(position-processList.size()).getUserName()));
                }else if(processList==null){
                    holder.tv_status.setText("已阅");
                    holder.tv_suggest.setText(StringUtil.isNullOrEmpty(receiveReportReadPersonVoList.get(position).getAdvise())?"":receiveReportReadPersonVoList.get(position).getAdvise());
                    holder.tv_date.setText(StringUtil.isNullOrEmpty(receiveReportReadPersonVoList.get(position).getReadTime())?"":receiveReportReadPersonVoList.get(position).getReadTime());
                    holder.tv_person.setText("阅文人:"+(StringUtil.isNullOrEmpty(receiveReportReadPersonVoList.get(position).getUserName())?"":receiveReportReadPersonVoList.get(position).getUserName()));
                }
            }
        }

        @Override
        public int getItemCount() {
            return ((processList!=null)?processList.size():0)+((receiveReportReadPersonVoList!=null)?receiveReportReadPersonVoList.size():0);
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            ImageView image;TextView tv_status;TextView tv_suggest;TextView tv_date;TextView tv_person;
            public ViewHolder(View itemView) {
                super(itemView);
                this.image = itemView.findViewById(R.id.image);
                this.tv_status = itemView.findViewById(R.id.tv_status);
                this.tv_suggest = itemView.findViewById(R.id.tv_suggest);
                this.tv_date = itemView.findViewById(R.id.tv_date);
                this.tv_person = itemView.findViewById(R.id.tv_person);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode ==RESULT_OK) {
            if(data.getStringExtra("position").equals("1")){
                finish();
            }
        }
    }
    public class ReadAdapter extends RecyclerView.Adapter<ReadAdapter.ViewHolder> {
        private List<ReceiveReportReadPersonVo> receiveReportReadPersonVoList;
        private int checkPosition=-1;//默认全不选

        public ReadAdapter(List<ReceiveReportReadPersonVo> receiveReportReadPersonVoList) {
            this.receiveReportReadPersonVoList = receiveReportReadPersonVoList;
        }

        @NonNull
        @Override
        public ReadAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_process_step, parent, false);
            ReadAdapter.ViewHolder viewHolder = new ReadAdapter.ViewHolder(itemView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull ReadAdapter.ViewHolder holder, int position) {
            holder.linearLayout2.setVisibility(View.GONE);
            holder.tv_suggest.setText(StringUtil.isNullOrEmpty(receiveReportReadPersonVoList.get(position).getAdvise())?"":receiveReportReadPersonVoList.get(position).getAdvise());
            holder.tv_date.setText(StringUtil.isNullOrEmpty(receiveReportReadPersonVoList.get(position).getReadTime())?"":receiveReportReadPersonVoList.get(position).getReadTime());
            holder.tv_person.setText(StringUtil.isNullOrEmpty(receiveReportReadPersonVoList.get(position).getUserName())?"":receiveReportReadPersonVoList.get(position).getUserName());
        }

        @Override
        public int getItemCount() {
            return receiveReportReadPersonVoList.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            ImageView image;TextView tv_status;TextView tv_suggest;TextView tv_date;TextView tv_person;
            LinearLayout linearLayout2;
            public ViewHolder(View itemView) {
                super(itemView);
                this.image = itemView.findViewById(R.id.image);
                this.tv_status = itemView.findViewById(R.id.tv_status);
                this.tv_suggest = itemView.findViewById(R.id.tv_suggest);
                this.tv_date = itemView.findViewById(R.id.tv_date);
                this.tv_person = itemView.findViewById(R.id.tv_person);
                this.linearLayout2 = itemView.findViewById(R.id.linearLayout2);
            }
        }
    }

}